import request from 'request';
import zlib from 'zlib';

export default class PPXMonitor {

    constructor(option) {
        this.listenerPool = new Array();
        this.config = option.monitor;
        this.blocks = new Map();
    }

    monitoring() {
        return new Promise((resolve, reject) => {
            request("http://api.myhloli.com/ppx.php", {
                method: 'GET',
                headers: {
                    'Accept-Encoding': 'gzip, deflate',
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"
                }
            }, (error, response, body) => {
                if (error) {
                    reject({ reason: "错误的响应", code: 500, message: error });
                } else if (response.statusCode !== 200) {
                    reject({ reason: "错误的响应", code: response.statusCode, message: response.statusMessage });
                } else if (!body) {
                    reject({ reason: "错误的响应，无内容", code: 204, message: "" });
                } else {
                    resolve(JSON.parse(body));
                }
            });
        });
    }

    start() {
        this.monitoring().then(data => {
            const blocks = data.pool.blocks;
            if (blocks instanceof Array && blocks.length > 0) {
                for (let i = 0; i < blocks.length; i++) {
                    let slice = blocks[i].split(':');
                    let height = blocks[++i];
                    if (slice.length < 5 && !this.blocks.has(slice[0])) {
                        this.blocks.set(slice[0], {
                            hash: slice[0],
                            height: height,
                            diff: slice[2],
                            since: new Date(slice[1] * 1000)
                        });
                        this.listenerPool.forEach(func => {
                            func.call(this, this.blocks);
                        });
                    } else if (this.blocks.has(slice[0])) {
                        this.blocks.delete(slice[0]);
                        this.listenerPool.forEach(func => {
                            func.call(this, this.blocks);
                        });
                    }
                }
            }
        }).catch(event => {
            console.error(event.reason + ' ，响应码：' + event.code + " ，响应内容： " + event.message);
        }).then(() => {
            setTimeout(this.start.bind(this), this.config.interval);
        });
    }

    addListener(listener) {
        if (typeof listener === 'function') {
            this.listenerPool.push(listener);
        }
    }

    info() {
        return {
            name: 'ppx',
            priority: 1000,
            instance: this
        };
    }
}